﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;

namespace Fa.Kanbox.API.Demo
{
    public partial class UcProgress : UserControl
    {
        public UcProgress()
        {
            InitializeComponent();
        }
        private object _UserState;

        public void DownloadFile(KbListContentInfo info, string savePath)
        {
            var fileName = Path.GetFileName(info.FullPath);
            label1.Text = string.Format("文件:{0},下载中", fileName);
            MyGlobal.ApiClient.DownloadAsync(info.FullPath, savePath, (ages) =>
            {
                _UserState = ages.UserState;
                progressBar1.Value = ages.ProgressPercentage;
            }, (ages) =>
            {
                if (ages.Cancelled)
                {
                    label1.Text = string.Format("文件:{0},用户取消下载", fileName);
                }
                else if (ages.Error != null)
                {
                    label1.Text = string.Format("文件:{0},文件下载发生异常{1}", fileName, ages.Error.Message);
                }
                else
                {
                    label1.Text = string.Format("文件:{0},下载完毕", fileName);
                }
                bunCancel.Visible = false;
            });
        }
        public void UploadFile(string targetPath, string sourceFilePath, Action<UploadFileCompletedEventArgs> uploadFileCompletedAction)
        {
            var fileName = Path.GetFileName(sourceFilePath);
            label1.Text = string.Format("文件:{0},上传中", fileName);
            MyGlobal.ApiClient.UploadAsync(targetPath, sourceFilePath, (ages) =>
            {
                _UserState = ages.UserState;
                progressBar1.Value = ages.ProgressPercentage;
            }, (ages) =>
            {
                if (ages.Cancelled)
                {
                    label1.Text = string.Format("文件:{0},用户取消上传", fileName);
                }
                else if (ages.Error != null)
                {
                    label1.Text = string.Format("文件:{0},文件上传发生异常{1}", fileName, ages.Error.Message);
                }
                else
                {
                    label1.Text = string.Format("文件:{0},上传完毕", fileName);
                }
                if (uploadFileCompletedAction != null)
                {
                    uploadFileCompletedAction(ages);
                }
                bunCancel.Visible = false;
            });
        }
        
        private void bunCancel_Click(object sender, EventArgs e)
        {
            if (progressBar1.Value != 100)
            {
                if (_UserState != null)
                {
                    (_UserState as WebClient).CancelAsync();
                }
            }
        }
    }
}
